//
//  PersonalHomePageViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/17.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "PersonalHomePageViewController.h"
#import "HallModel.h"
#import "ComplaintsViewController.h"
#import "DeliveryDetailsViewController.h"
static NSString *cellPath = @"PersonalHomeCell";
@interface PersonalHomePageViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton *cancelBtn;
}
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *allHallAry;
@property (nonatomic, strong)UserAccountModel *model;
@property (nonatomic, strong)HallModel *Phonemodel;
@property (nonatomic, assign)BOOL isMine;

@end

@implementation PersonalHomePageViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(callPhonesNotifice:) name:@"callPhones" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"callPhones" object:nil];
}


- (void)callPhonesNotifice:(NSNotification *)center
{
    NSString *timeStr = [center object];
    Student *stu = [Student studentWith:_Phonemodel.userheadImg name:_Phonemodel.username Phone:_Phonemodel.userphone Times:timeStr];
    BOOL isInsert = [StudentFMDNManager addStudent:stu];
    
    if (isInsert) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入失败");
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    [self requestSelectUser];
    [self requestAllHallList];
}

- (void)creatUI
{
    self.navigationItem.title = @"发货人信息";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    CGFloat H = SCREEN_HEIGHT-STA_NAV_HEIGHT-65*displaywidth-SCREER_HeiX;
    UserAccountModel *model = [UserAccountModel shareMange];
    if (model.ID == [_userid integerValue])
    {
        self.view.backgroundColor = BacksColor;
        _isMine = YES;
        H = SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX;
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, H) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
   
    if (!_isMine)
    {
        cancelBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displayheight-SCREER_HeiX, SCREEN_WIDTH/2-22.5*displaywidth, 45*displayheight) ImageName:nil Target:self Action:@selector(collectionAction) Title:@"收藏" Font:16.0];
        cancelBtn.backgroundColor = RGB(87, 107, 149);
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        cancelBtn.layer.cornerRadius = 5;
        cancelBtn.layer.masksToBounds = YES;
        [self.view addSubview:cancelBtn];
        
        UIButton *backBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2+7.5*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-55*displayheight-SCREER_HeiX, SCREEN_WIDTH/2-22.5*displaywidth, 45*displayheight) ImageName:nil Target:self Action:@selector(complaintsAction) Title:@"投诉" Font:16.0];
        backBtn.backgroundColor = YellowColor;
        [backBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        backBtn.layer.cornerRadius = 5;
        backBtn.layer.masksToBounds = YES;
        [self.view addSubview:backBtn];
    }
}

//收藏
- (void)collectionAction
{
    WEAKSELF;
    NSDictionary *dic = @{@"joinId":_userid,
                          @"type":@"3"
                          };
    [HYBaseHandler requestWithTheFormUrl:SERVER_phoneBook Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            NSString *msg = s_str(obj[@"msg"]);
            if (![msg containsString:@"取消"])
            {
                [LTools showMBProgressWithText:@"收藏成功" addToView:weakSelf.view];
                [cancelBtn setTitle:@"已收藏" forState:UIControlStateNormal];
            }
            else
            {
                [LTools showMBProgressWithText:@"取消收藏成功" addToView:weakSelf.view];
                [cancelBtn setTitle:@"收藏" forState:UIControlStateNormal];
            }
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//投诉
- (void)complaintsAction
{
    ComplaintsViewController *vc = [[ComplaintsViewController alloc] init];
    vc.titStr = @"投诉发货人";
    vc.joinStr = _userid;
    vc.typeStr = @"2";
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 2;
    }
    return _allHallAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = BacksColor;
    if (_model)
    {
        if (indexPath.section == 0)
        {
            if (indexPath.row == 0)
            {
                UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100*displaywidth)];
                whiteView.backgroundColor = [UIColor whiteColor];
                [cell.contentView addSubview:whiteView];
                UIImageView *faceView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 12.5*displaywidth, 75*displaywidth, 75*displaywidth) ImageName:@"morenFace"];
                if (_model.headImg.length > 0)
                {
                    [faceView sd_setImageWithURL:URL(_model.headImg) placeholderImage:IMAGE(@"morenFace")];
                }
                faceView.contentMode = UIViewContentModeScaleAspectFill;
                faceView.layer.cornerRadius = 37.5*displaywidth;
                faceView.layer.masksToBounds = YES;
                [whiteView addSubview:faceView];
                UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(100*displaywidth, 15*displaywidth, SCREEN_WIDTH- 140*displaywidth, 25*displaywidth) Font:15.0 Text:_model.username Color:RGB(51, 51, 51)];
                nameLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
                CGRect bounds = [nameLab.text boundingRectWithSize:CGSizeMake(1000, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
                CGFloat W = bounds.size.width + 10*displaywidth;
                if (bounds.size.width > SCREEN_WIDTH- 150*displaywidth)
                {
                    W = SCREEN_WIDTH- 140*displaywidth;
                }
                nameLab.frame = CGRectMake(100*displaywidth, 15*displaywidth, W, 25*displaywidth);
                nameLab.lineBreakMode = NSLineBreakByTruncatingTail;
                nameLab.adjustsFontSizeToFitWidth = NO;
                [whiteView addSubview:nameLab];
                if (_model.isIdentify == 1)
                {
                    UILabel *shiLab = [ZCControl createLabelWithFrame:CGRectMake(W+105*displaywidth, 20*displayheight, 15*displaywidth, 15*displayheight) Font:10.0 Text:@"实" Color:[UIColor whiteColor]];
                    shiLab.textAlignment = NSTextAlignmentCenter;
                    shiLab.backgroundColor = RGB(204, 153, 102);
                    [whiteView addSubview:shiLab];
                }
                UILabel *numLab = [ZCControl createLabelWithFrame:CGRectMake(100*displaywidth, 40*displayheight, SCREEN_WIDTH- 115*displaywidth, 25*displayheight) Font:13.0 Text:[NSString stringWithFormat:@"发货%@次   投诉%ld次",_model.cargoCount,_model.complainCount] Color:RGB(204, 204, 204)];
                NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"发货%@次   投诉%ld次",_model.cargoCount,_model.complainCount]];
                NSRange titleRange = [[title string]rangeOfString:[NSString stringWithFormat:@"%@",_model.cargoCount]];
                NSRange titleRange2 = [[title string]rangeOfString:[NSString stringWithFormat:@"诉%ld",_model.complainCount]];
                NSRange titR3 = NSMakeRange(titleRange2.location+1, titleRange2.length-1);
                [title addAttribute:NSForegroundColorAttributeName value:RGB(136, 136, 136) range:titleRange];
                [title addAttribute:NSForegroundColorAttributeName value:RGB(136, 136, 136) range:titR3];
                numLab.attributedText = title;
                [whiteView addSubview:numLab];
                UILabel *addressLab = [ZCControl createLabelWithFrame:CGRectMake(100*displaywidth, 65*displaywidth, SCREEN_WIDTH-115*displaywidth, 25*displaywidth) Font:13.0 Text:_model.address Color:RGB(136, 136, 136)];
                [whiteView addSubview:addressLab];
            }
            else
            {
                UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 29.5*displaywidth, SCREEN_WIDTH-30*displaywidth, 1*displaywidth)];
                aView.backgroundColor = RGB(204, 204, 204);
                [cell.contentView addSubview:aView];
                UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2-75*displaywidth, 15*displayheight, 150*displaywidth, 30*displayheight) Font:13.0 Text:@"当前货主所发货源" Color:RGB(204, 204, 204)];
                titLab.backgroundColor = BacksColor;
                titLab.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:titLab];
                
            }
        }
    }
    if (indexPath.section == 1)
    {
        if (_allHallAry.count > 0)
        {
            HallModel *haModel = _allHallAry[indexPath.row];
            CGFloat W = SCREEN_WIDTH-20*displaywidth;
            UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, 0, W, 120*displaywidth)];
            whiteView.backgroundColor = [UIColor whiteColor];
            whiteView.layer.cornerRadius = 5*displaywidth;
            whiteView.layer.masksToBounds = YES;
            [cell.contentView addSubview:whiteView];
            CGFloat Width = 0;
            UILabel *startLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 10*displaywidth, 160*displaywidth, 25*displaywidth) Font:15.0 Text:[NSString stringWithFormat:@"%@%@%@",haModel.shipmentcity,haModel.shipmentdistrict,haModel.shipmentname] Color:BlaTitColor];
            startLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
            CGRect bound1 = [startLab.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObject:NormalFontWithSize(15.0+fontScale) forKey:NSFontAttributeName] context:nil];
            startLab.frame = CGRectMake(10*displaywidth, 10*displaywidth, bound1.size.width+5*displaywidth, 25*displaywidth);
            Width += (bound1.size.width+15*displaywidth);
            [whiteView addSubview:startLab];
            UIImageView *imgBView = [ZCControl createImageViewWithFrame:CGRectMake(Width, 15*displaywidth, 30*displaywidth, 15*displaywidth) ImageName:@"zxli_icon01"];
            imgBView.contentMode = UIViewContentModeScaleAspectFit;
            [whiteView addSubview:imgBView];
            Width+=30*displaywidth;
            UILabel *stopLab = [ZCControl createLabelWithFrame:CGRectMake(Width, 10*displaywidth, W-Width-10*displaywidth, 25*displaywidth) Font:15.0 Text:[NSString stringWithFormat:@"%@%@%@",haModel.destinationCity,haModel.destinationDistrict,haModel.destinationname] Color:BlaTitColor];
            stopLab.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
            [whiteView addSubview:stopLab];
            NSString *volStr = haModel.cargoType;
            if (![haModel.weight isEqualToString:@""])
            {
                volStr = [volStr stringByAppendingString:[NSString stringWithFormat:@"/%@吨",haModel.weight]];
            }
            if (![haModel.volume isEqualToString:@""])
            {
                volStr = [volStr stringByAppendingString:[NSString stringWithFormat:@"/%@立方",haModel.volume]];
            }
            UILabel *volumeLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 35*displaywidth, W-20*displaywidth, 20*displaywidth) Font:13.0 Text:volStr Color:YellowColor];
            [whiteView addSubview:volumeLab];
            NSString *timeStr = haModel.createDtm;
            if (timeStr.length > 10)
            {
                timeStr = [timeStr substringToIndex:10];
            }
            UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 55*displaywidth, W/2, 20*displaywidth) Font:13.0 Text:timeStr Color:RGB(141, 147, 154)];
            [whiteView addSubview:timeLab];
            UILabel *priceLab = [ZCControl createLabelWithFrame:CGRectMake(W-160*displaywidth, 55*displaywidth, 150*displaywidth, 20*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"￥%@元左右",haModel.price] Color:RGB(189, 189, 189)];
            priceLab.textAlignment = NSTextAlignmentRight;
            NSMutableAttributedString *title2 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"￥%@元左右",haModel.price]];
            NSRange titleRange2 = [[title2 string]rangeOfString:[NSString stringWithFormat:@"￥%@",haModel.price]];
            [title2 addAttribute:NSForegroundColorAttributeName value:YellowColor range:titleRange2];
            priceLab.attributedText = title2;
            [whiteView addSubview:priceLab];
            
            UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(10*displaywidth, 80*displaywidth, W-20*displaywidth, 1*displaywidth)];
            lineAview.backgroundColor = BacksColor;
            [whiteView addSubview:lineAview];
            
            UILabel *postLab = [ZCControl createLabelWithFrame:CGRectMake(10*displaywidth, 85*displaywidth, W-110*displaywidth, 30*displaywidth) Font:11.0 Text:[NSString stringWithFormat:@"%@人查看   %@人已联系",haModel.viewCount,haModel.callCount] Color:RGB(189, 189, 189)];
            [whiteView addSubview:postLab];
            NSString *titString = @"联系货主";
            if (_isMine)
            {
                titString = @"删除";
            }
            UIButton *btn = [ZCControl createButtonWithFrame:CGRectMake(W-100*displaywidth, 85*displaywidth, 90*displaywidth, 30*displaywidth) ImageName:nil Target:self Action:@selector(callHallPeopleAction:) Title:titString Font:13.0];
            btn.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.0];
            btn.backgroundColor = [UIColor clearColor];
            [btn setTitleColor:ThemeColor forState:UIControlStateNormal];
            btn.contentVerticalAlignment = 0;
            btn.contentHorizontalAlignment = 2;
            btn.tag = 1000+indexPath.row;
            [whiteView addSubview:btn];
            
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        HallModel *haModel = _allHallAry[indexPath.row];
        DeliveryDetailsViewController *vc = [[DeliveryDetailsViewController alloc] init];
        vc.idstr = s_str(haModel.ID);
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            return 100*displaywidth;
        }
        return 55*displaywidth;
    }
    return 130*displaywidth;
}

- (void)callHallPeopleAction:(UIButton *)btn
{
    NSInteger index = btn.tag-1000;
    HallModel *model = _allHallAry[index];
    if (_isMine)
    {
        //删除
        WEAKSELF;
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除该条货源信息" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
      
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakSelf requestDeleteCargo:s_str(model.ID)];
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    else
    {
        _Phonemodel = model;
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",model.userphone]]];

    }
}

- (void)requestDeleteCargo:(NSString *)idstr
{
    WEAKSELF;
    NSDictionary *dic = @{@"id":idstr};
    [HYBaseHandler requestWithTheFormUrl:SERVER_cargoDelete Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [LTools showMBProgressWithText:@"删除成功" addToView:weakSelf.view];
            [weakSelf requestAllHallList];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)requestSelectUser
{
    
    WEAKSELF;
    NSDictionary *dic = @{@"id":_userid};
    [HYBaseHandler requestWithTheFormUrl:SERVER_userSelect Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _model = [UserAccountModel mj_objectWithKeyValues:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([_model.isCollect integerValue] == 1)
                {
                    [cancelBtn setTitle:@"已收藏" forState:UIControlStateNormal];
                }
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
       
    }];
}

//货源信息
- (void)requestAllHallList
{
    WEAKSELF;
    NSDictionary *dic = @{@"user.id":_userid,
                          @"size":@"9999"};
    [HYBaseHandler requestWithTheFormUrl:SERVER_cargoList Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            weakSelf.allHallAry = [HallModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
      
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
